package com.cloud.alibaba.oauthserver.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * created by wuquan at 05/18/2021
 * ^_^ ^_^
 * 授权服务中心
 */
@Configuration
@EnableAuthorizationServer
public class CustomAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;
    //认证管理器
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private AuthorizationCodeServices authorizationCodeServices;


    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private ClientDetailsService clientDetailsService;

    //令牌管理服务
    public AuthorizationServerTokenServices authorizationServerTokenServices() {
        DefaultTokenServices services = new DefaultTokenServices();
        services.setClientDetailsService(clientDetailsService);//客户端信息服务
        services.setTokenStore(tokenStore);
        services.setSupportRefreshToken(true);
        //token active time
        services.setAccessTokenValiditySeconds(1800);
        services.setRefreshTokenValiditySeconds(36000);

        return services;
    }



    /*
    客户端服务详情
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        /*
        clients.withClientDetails(new ClientDetailsService() {
            @Override
            public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
                return null;
            }
        });*/

        clients.inMemory()
                    .withClient("client-1")
                    .secret(passwordEncoder.encode("wuquan"))
                    //授权模式
                    .authorizedGrantTypes("password", "authorization_code")
                    .scopes("read")
                    .accessTokenValiditySeconds(1800)
                    //允许访问的服务
                    .resourceIds("client-8081", "client-9093")
                    //跳转路径
                    .redirectUris("https://www.baidu.com")
                .and()
                    .withClient("client01_app")
                    .secret(passwordEncoder.encode("wuquan"))
                    //授权模式
                    .authorizedGrantTypes("password")
                    .scopes("read")
                    .accessTokenValiditySeconds(1800)
                    //允许访问的服务
                    .resourceIds("client-8081");
    }

     /*
    令牌访问端点
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        /*1，授权类型：
              authenticationManager： 认证管理器，选择密码授权类型
              userDetailsService：如果配置这个则需要自己实现UserDetailsService接口，
              authorizationCodeServices：设置授权码服务
              implicitGrantService：设置隐式授权模式
              tokenGrant：TokenGrant接口实现，授权完全交给自己掌控，忽略上面集中模式
          2，授权访问端点URL：

         */
        endpoints.authenticationManager(authenticationManager)
                .authorizationCodeServices(authorizationCodeServices)
                .tokenServices(authorizationServerTokenServices())
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);

    }


    /* 访问安全配置
    校验令牌:需要携带 appId，app secret
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {

        security.allowFormAuthenticationForClients()
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()");

    }


}



